//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <ddk.h>

Int32 SubThreadForTest02(void *pvPara)
{
    while (1) DzYield();

    return NOERROR;
}

Int32 AbortMainThreadNow(void *pvPara)
{
    IThread     *pIMainThread = (IThread *)pvPara;
    int         nThreadId;
    ECode     ec;

    ec = pIMainThread->GetId(&nThreadId);
    if (FAILED(ec)) {
        kprintf("[in sub]Get thread id failed, the ec = 0x%08x\n", ec);
        assert(0);

        return ec;
    }

    kprintf("[in sub]The main thread id is %d\n", nThreadId);

    ec = pIMainThread->Abort();
    if (FAILED(ec)) {
        kprintf("Abort the main thread failed, the ec = 0x%08x\n", ec);
        assert(0);

        return ec;
    }

    pIMainThread->Release();

    return NOERROR;
}

EXTERN void SubAbortMainThread()
{
    ECode         ec;

    for (int i = 0; i < 100; i++) {
        ec = DzCreateKernelThread(SubThreadForTest02, (void *)0, 0,
                                    (ThreadPriorityRank)0xFFFFEEEE, NULL);

        if (FAILED(ec)) {
            kprintf("Create thread %d failed, the ec = 0x%08x\n",i,ec);
            assert(0);

            return;
        }

        DzYield();
    }

    ec = DzSleep(DzMillisecondsToTicks(10));
    if (NOERROR != ec) {
        kprintf("The sleep not success, the ec = 0x%08x\n", ec);
        assert(0);

        return;
    }

    IThread     *pICurrentThread;
    int         nThreadId;

    ec = DzGetCurrentThread(&pICurrentThread);
    if (FAILED(ec)) {
        kprintf("Get current thread failed, the ec = 0x%08x\n", ec);
        assert(0);

        return;
    }

    ec = pICurrentThread->GetId(&nThreadId);
    if (FAILED(ec)) {
        kprintf("Get thread id failed, the ec = 0x%08x\n", ec);
        assert(0);

        return;
    }

    kprintf("The main thread id is %d\n", nThreadId);

    ec = DzCreateKernelThread(AbortMainThreadNow, (void *)pICurrentThread,
                        CreateThreadFlag_System, ThreadPriorityRank_Normal, NULL);
    if (FAILED(ec)) {
        kprintf("Create thread failed, the ec = 0x%08x\n", ec);
        assert(0);

        return;
    }
}
